package com.ruoyi.mdm.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mdm.domain.SearchConditionInfo;
import com.ruoyi.mdm.domain.SkuInfoEntity;
import com.ruoyi.mdm.domain.SkumInfoEntity;
import com.ruoyi.mdm.domain.SpuInfoEntity;
import com.ruoyi.mdm.domain.dto.SkuMasterDto;
import com.ruoyi.mdm.domain.dto.SkuMergeMasterDto;
import com.ruoyi.mdm.domain.dto.SkuProductMasterDto;
import com.ruoyi.mdm.mapper.MasterDataMapper;
import com.ruoyi.mdm.service.IMasterDataService;
import com.ruoyi.mdm.service.ISkuInfoService;
import com.ruoyi.mdm.service.ISkumInfoService;
import com.ruoyi.mdm.service.ISpuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.erhlc.ElasticsearchAggregations;
import org.springframework.data.elasticsearch.core.AggregationsContainer;

import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MasterDataServiceImpl implements IMasterDataService {

    @Autowired
    private MasterDataMapper masterDataMapper;

    @Autowired
    private ISkuInfoService skuInfoService;

    @Autowired
    private ISkumInfoService skumInfoService;

    @Autowired
    private ISpuInfoService spuInfoService;

    /**
     * 高级查询数据服务信息
     *
     * @param searchConditionInfo 检索条件
     * @return 数据服务信息
     */
    @Override
    public List<?> selectMasterData(SearchConditionInfo searchConditionInfo) {

        // 搜索维度必须
        if (searchConditionInfo.getSearchDimension() == null) {
            throw new ServiceException("搜索维度不能为空！");
        }

        // 根据搜索维度
        switch (searchConditionInfo.getSearchDimension()) {
            case "SKU":
                return masterDataMapper.selectSkuMasterData(searchConditionInfo);
            case "SKUM":
                return masterDataMapper.selectSkuMergeMasterData(searchConditionInfo);
            case "SPU":
                return masterDataMapper.selectSkuProductMasterData(searchConditionInfo);
            default:
                return null;
        }
    }

    /**
     * ES模糊查询数据服务信息
     *
     * @param searchConditionInfo 检索条件
     * @return 数据服务信息
     */
    @Override
    public Object searchMasterData(SearchConditionInfo searchConditionInfo) {

        // 搜索维度必须
        if (searchConditionInfo.getSearchDimension() == null) {
            throw new ServiceException("搜索维度不能为空！");
        }

        // 根据搜索维度
        TableDataInfo rspData = new TableDataInfo();

        switch (searchConditionInfo.getSearchDimension()) {
            case "SKU":

                // SKUM ES 模糊检索
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setChannelCode(searchConditionInfo.getChannelCode());

                skuInfoEntity.setSkuSalesChannel(searchConditionInfo.getSalesChannelCode());
                skuInfoEntity.setBarCode(searchConditionInfo.getBarCode());
                skuInfoEntity.setGoodsCode(searchConditionInfo.getGoodsCode());
                skuInfoEntity.setOwnerId(searchConditionInfo.getOwnerIds());
                skuInfoEntity.setSalePrice(searchConditionInfo.getSalePrice());

                // 判断关键字是否为数字
                if (StringUtils.isNotEmpty(searchConditionInfo.getKeyword())) {
                    if (searchConditionInfo.getKeyword().matches("-?\\d+(\\.\\d+)?")) {
                        skuInfoEntity.setSalePrice(new BigDecimal(searchConditionInfo.getKeyword()));
                        skuInfoEntity.setKeyword(null);
                    } else {
                        skuInfoEntity.setKeyword(searchConditionInfo.getKeyword());
                    }
                }

                skuInfoEntity.setPage(searchConditionInfo.getPageNum()-1);
                skuInfoEntity.setSize(searchConditionInfo.getPageSize());
                SearchHits<SkuInfoEntity> searchSkuHits = skuInfoService.searchSkuInfo(skuInfoEntity);

                // 如果不为空 并且是数字 并且用价格检索不到 再用产品编码
                if (StringUtils.isNotEmpty(searchConditionInfo.getKeyword())) {
                    if (searchConditionInfo.getKeyword().matches("-?\\d+(\\.\\d+)?")) {

                        if (searchSkuHits.getTotalHits() == 0) {
                            // 产品编码作为条件
                            skuInfoEntity.setSalePrice(null);
                            skuInfoEntity.setGoodsCode(searchConditionInfo.getKeyword());
                            searchSkuHits = skuInfoService.searchSkuInfo(skuInfoEntity);

                            if (searchSkuHits.getTotalHits() == 0) {
                                skuInfoEntity.setGoodsCode(null);
                                skuInfoEntity.setKeyword(searchConditionInfo.getKeyword());
                                searchSkuHits = skuInfoService.searchSkuInfo(skuInfoEntity);
                            }
                        }
                    }
                }

                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("查询成功");
                List<SkuMasterDto> skuMasterDtoList = new ArrayList<>();
                searchSkuHits.forEach(skuInfoSearchHit -> {
                    SkuMasterDto skuMasterDto = new SkuMasterDto();
                    BeanUtils.copyProperties(skuInfoSearchHit.getContent(), skuMasterDto);

                    // 日期转换
                    skuMasterDto.setSaleBeginDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getSaleBeginDate()));
                    skuMasterDto.setSaleEndDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getSaleEndDate()));
                    skuMasterDto.setUpdateDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getUpdateDate()));
                    skuMasterDto.setTransferDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getTransferDate()));
                    skuMasterDto.setEtlInsertTime(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getEtlInsertTime()));
                    skuMasterDto.setBizDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getBizDate()));
                    skuMasterDto.setSnycDate(DateUtils.parseStrToDate(skuInfoSearchHit.getContent().getSnycDate()));

                    if (skuInfoSearchHit.getContent().getSkuId() != null) {
                        skuMasterDto.setId(skuInfoSearchHit.getContent().getSkuId());
                    }
                    log.info("es data skuMasterDto={}",skuMasterDto.toString());
                    skuMasterDtoList.add(skuMasterDto);
                });
                rspData.setRows(skuMasterDtoList);

                // 去重后总数 计算不准确
//                Aggregations aggregations = searchSkuHits.getAggregations();
//                Cardinality cardinality = aggregations.get("total_size");
//                int total = (int) cardinality.getValue();
//
//                if (total < searchSkuHits.getTotalHits()) {
//                    rspData.setTotal(total);
//                } else {
//                    rspData.setTotal(searchSkuHits.getTotalHits());
//                }
// 获取聚合结果
                AggregationsContainer<?> aggregations = searchSkuHits.getAggregations();

                // 转换为Elasticsearch 7.x的Aggregations
                if (aggregations instanceof ElasticsearchAggregations) {
                    org.elasticsearch.search.aggregations.Aggregations esAggregations =
                            ((ElasticsearchAggregations) aggregations).aggregations();

                    // 现在可以使用get方法
                    Terms distinctValues = esAggregations.get("distinct_values");
//                Terms distinctValues = searchSkuHits.getAggregations().get("distinct_values");
                rspData.setTotal(distinctValues.getBuckets().size());
                }

                return rspData;
            case "SKUM":

                // SKUM ES 模糊检索
                SkumInfoEntity skumInfoEntity = new SkumInfoEntity();
                skumInfoEntity.setKeyword(searchConditionInfo.getKeyword());
                skumInfoEntity.setOwnerId(searchConditionInfo.getOwnerIds());
                skumInfoEntity.setSkumSalePrice(searchConditionInfo.getSalePrice());
                skumInfoEntity.setPage(searchConditionInfo.getPageNum()-1);
                skumInfoEntity.setSize(searchConditionInfo.getPageSize());
                SearchHits<SkumInfoEntity> searchSkumHits = skumInfoService.searchSkumInfo(skumInfoEntity);

                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("查询成功");
                List<SkuMergeMasterDto> skuMergeMasterDtoList = new ArrayList<>();
                searchSkumHits.forEach(skumInfoSearchHit -> {
                    SkuMergeMasterDto skuMergeMasterDto = new SkuMergeMasterDto();
                    BeanUtils.copyProperties(skumInfoSearchHit.getContent(), skuMergeMasterDto);
                    skuMergeMasterDtoList.add(skuMergeMasterDto);
                });
                rspData.setRows(skuMergeMasterDtoList);
                rspData.setTotal(searchSkumHits.getTotalHits());

                return rspData;
            case "SPU":

                // SPU ES 模糊检索
                SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
                spuInfoEntity.setKeyword(searchConditionInfo.getKeyword());
                spuInfoEntity.setOwnerId(searchConditionInfo.getOwnerIds());
                spuInfoEntity.setPage(searchConditionInfo.getPageNum()-1);
                spuInfoEntity.setSize(searchConditionInfo.getPageSize());
                SearchHits<SpuInfoEntity> searchSpuHits = spuInfoService.searchSpuInfo(spuInfoEntity);

                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("查询成功");
                List<SkuProductMasterDto> skuProductMasterDtoList = new ArrayList<>();
                searchSpuHits.forEach(spuInfoSearchHit -> {
                    SkuProductMasterDto skuProductMasterDto = new SkuProductMasterDto();
                    BeanUtils.copyProperties(spuInfoSearchHit.getContent(), skuProductMasterDto);
                    skuProductMasterDtoList.add(skuProductMasterDto);
                });
                rspData.setRows(skuProductMasterDtoList);
                rspData.setTotal(searchSpuHits.getTotalHits());

                return rspData;
            default:
                return null;
        }
    }

}
